package com.example.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.Result;
import com.example.common.SystemConstants;
import com.example.domain.Shop;
import com.example.mapper.ShopMapper;
import com.example.service.ShopService;
import com.example.utils.RedisUtils;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

import static com.example.common.RedisContants.CACHE_SHOP_KEY;
import static com.example.common.RedisContants.SHOP_GEO_KEY;

/**
 * @author chenliang
 * @description 针对表【tb_shop】的数据库操作Service实现
 * @createDate 2024-06-19 20:03:56
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop>
        implements ShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 查询店铺缓存——缓存无效key解决缓存穿透
     *
     * @param id
     * @return
     */
    @Override
    public Result<Shop> queryById(Long id) {
        //缓存穿透——设置无效Key
        Shop shop = redisUtils.queryWithPassThrough(id);
        //7、返回
        return Result.ok(shop);
    }

    /**
     * 查询店铺缓存——互斥锁解决缓存击穿
     *
     * @param id
     * @return
     */
    @Override
    public Result<Shop> queryById02(Long id) {
        //互斥锁解决缓存击穿
        Shop shop = redisUtils.queryWithMutex(id);
        if (shop == null) {
            return Result.fail("店铺不存在！！");
        }
        //7、返回
        return Result.ok(shop);
    }

    /**
     * 查询店铺缓存——逻辑过期解决缓存击穿
     *  todo 使用逻辑过期，需要先进行数据预热，添加逻辑过期时间
     *
     * @param id
     * @return
     */
    @Override
    public Result<Shop> queryById03(Long id) {
        //逻辑过期解决缓存击穿
        Shop shop = redisUtils.queryWithLogicExpire(id);

        if (shop == null) {
            return Result.fail("店铺不存在！！");
        }
        //7、返回
        return Result.ok(shop);
    }

    /**
     * 布隆过滤器解决缓存穿透问题
     *
     * @param id
     * @return
     */
    @Override
    public Shop bloomFilterById(Long id) {
        Shop shop = redisUtils.bloomFilterPassThrough(id);
        if (shop == null) {
            Result.fail("商品数据不存在");
        }
        //7、返回
        return shop;
    }

    /**
     * 更新商品数据
     * 数据缓存一致性
     * 先获取商品ID，更新数据库，然后删除缓存。
     *
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        //做个判断——需要确保id不为空
        if (id == null) {
            return Result.fail("店铺id不为空！！");
        }
        //1、更新数据库
        updateById(shop);
        //2、删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public boolean saveData(Shop shop) {
        Integer integer = redisUtils.InsertData(shop);
        return true;
    }

    /**
     * 根据商铺类型分页查询商铺信息
     *
     * @param typeId  商铺类型
     * @param current 页码
     * @return 商铺列表
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1、判断是否需要根据坐标查询
        if (x == null || y == null) {
            //无需坐标查询，根据商品类型数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        //2、计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        //3、查询redis,按照距离排序分页。结果：shopid、distance
        String key = SHOP_GEO_KEY + typeId;
        //命令语法：GEOSEARCH key FROMLONLAT 坐标 BYRADIUS 半径 单位 withdist
        GeoResults<RedisGeoCommands.GeoLocation<String>>
                results = stringRedisTemplate.opsForGeo()
                .search(key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs
                                .newGeoSearchArgs().includeDistance().limit(end)
                );
        //4、解析出id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            //没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        //4.1、截取from ~ end 的部分
        ArrayList<Object> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            //4.2、获取店铺id
            String shopStr = result.getContent().getName();
            ids.add(Long.valueOf(shopStr));
            //4.3、获取距离
            Distance distance = result.getDistance();
        });
        //5、根据id查询shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids)
                .last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            String shopId = shop.getId().toString();
            if (distanceMap.containsKey(shopId)) {  // 判断 distanceMap 中是否包含对应商铺的距离信 息
                shop.setDistance(distanceMap.get(shopId).getValue());
            } else {
                // 如果 distanceMap 中不包含对应商铺的距离信息，则使用默认值或者跳过该商铺的操作
                shop.setDistance((double) -1);  // 设置默认值 -1，表示距离未知
                // 或者使用 continue 跳过当前商铺的操作
            }
        }
        //6、返回
        return Result.ok(shops);
    }


}




